package lambdasinaction.chap3;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import lambdasinaction.chap3.MyLambdas.Apple.ApplePredicate;

/**
 * TODO
 *
 * @author Fish
 * @since 0.0.1 2018/7/19 10:46
 */
public class MyLambdas {

  public static void main(String[] args) {
    // Simple example
//    Runnable runnable = () -> {System.out.println("hello!");};
//    runnable.run();

    // Filtering with lambdas
    List<Apple> inventory = Arrays.asList(new Apple(130, "red"),
        new Apple(110, "red"),
        new Apple(30, "green"),
        new Apple(170, "green"));

//    List<Apple> redApple = filter(inventory, (Apple a) -> a.getColor().equals("red"));
//    System.out.println(redApple);

    Comparator<Apple> comparator = (Apple a1, Apple a2) -> a1.getWeight().compareTo(a2.getWeight());
    inventory.sort(comparator);
    System.out.println(inventory);
  }

  public static <T> List<T> filter(List<T> list, ApplePredicate<T> predicate) {
    List<T> result = new ArrayList<>();
    for (T t: list) {
      if (predicate.test(t)) {
        result.add(t);
      }
    }
    return result;
  }

  public static class Apple {

    private Integer weight;
    private String color;

    public Apple(Integer weight, String color) {
      this.weight = weight;
      this.color = color;
    }

    public Integer getWeight() {
      return weight;
    }

    public void setWeight(Integer weight) {
      this.weight = weight;
    }

    public String getColor() {
      return color;
    }

    public void setColor(String color) {
      this.color = color;
    }

    @Override
    public String toString() {
      return "Apple{" +
          "weight=" + weight +
          ", color='" + color + '\'' +
          '}';
    }

    @FunctionalInterface
    interface ApplePredicate<T> {
      boolean test(T a);
    }
  }

}
